package com.mao.server.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Dict;
import com.mao.server.annotation.AuthAccess;
import com.mao.server.annotation.HoneyLogs;
import com.mao.server.domain.enumuric.LogType;
import com.mao.server.utils.Result;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

@RestController
@RequestMapping("/file")
public class FileController {
    @Value("${applicationPort}")
    String applicationPort;

    @Value("${host}")
    String host;

    private static final String ROOT_PATH = System.getProperty("user.dir") + File.separator + "serverFiles";

    @HoneyLogs(operation = "文件", type = LogType.ADD)
    @PostMapping("/uploadFile")
    public Result uploadFile(MultipartFile file) throws IOException {
        String fileOriginalName = file.getOriginalFilename();
        String mainName = FileUtil.mainName(fileOriginalName);
        String extName = FileUtil.extName(fileOriginalName);

        // 创建 serverFiles
        if (!FileUtil.exist(ROOT_PATH)) FileUtil.mkdir(ROOT_PATH);

        // 重命名已经上传的文件
        if (FileUtil.exist(ROOT_PATH + File.separator + fileOriginalName)) {
            fileOriginalName = System.currentTimeMillis() + "_" + mainName + "." + extName;
        }
        File saveFile = new File(ROOT_PATH + File.separator + fileOriginalName);
        file.transferTo(saveFile);

        String fileUrl = "http://" + host + ":" + applicationPort + "/file/downloadFile/" + fileOriginalName;

        return Result.success(fileUrl);
    }

    @AuthAccess
    @GetMapping("/downloadFile/{fileName}")
    public void downloadFile(@PathVariable String fileName, HttpServletResponse response) throws IOException {
        //response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));  // 附件下载
        response.addHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(fileName, "UTF-8"));  // 预览
        String filePath = ROOT_PATH + File.separator + fileName;
        if (!FileUtil.exist(filePath)) {
            return;
        }
        byte[] bytes = FileUtil.readBytes(filePath);
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();
    }

    @HoneyLogs(operation = "文件", type = LogType.ADD)
    @PostMapping("/editor/uploadFile")
    public Dict editorUpload(@RequestParam MultipartFile file, @RequestParam String type) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String mainName = FileUtil.mainName(originalFilename);
        String extName = FileUtil.extName(originalFilename);

        if (!FileUtil.exist(ROOT_PATH)) {
            FileUtil.mkdir(ROOT_PATH);
        }

        // 如果当前上传的文件已经存在了，那么这个时候我就要重名一个文件名称
        if (FileUtil.exist(ROOT_PATH + File.separator + originalFilename)) {
            originalFilename = System.currentTimeMillis() + "_" + mainName + "." + extName;
        }

        File saveFile = new File(ROOT_PATH + File.separator + originalFilename);
        file.transferTo(saveFile);  // 存储文件到本地的磁盘里面去

        String url = "http://" + host + ":" + applicationPort + "/file/downloadFile/" + originalFilename;

        if ("img".equals(type)) {
            // 上传图片
            return Dict.create().set("errno", 0).set("data", CollUtil.newArrayList(Dict.create().set("url", url)));
        } else if ("video".equals(type)) {
            // 上传视频
            return Dict.create().set("errno", 0).set("data", Dict.create().set("url", url));
        }
        return Dict.create().set("errno", 0);
    }
}
